package com.zm.admin.zmeng.controller;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zm.admin.annotation.SysLogTag;
import com.zm.admin.utils.ResultBean;
import com.zm.admin.zmeng.domain.ZmDict;
import com.zm.admin.zmeng.domain.ZmDictInfo;
import com.zm.admin.zmeng.domain.ZmSysLog;
import com.zm.admin.zmeng.domain.ZmVisitor;
import com.zm.admin.zmeng.dto.DictDto;
import com.zm.admin.zmeng.dto.DictInfoDto;
import com.zm.admin.zmeng.dto.SysLogDto;
import com.zm.admin.zmeng.mapper.ZmDictInfoMapper;
import com.zm.admin.zmeng.mapper.ZmDictMapper;
import com.zm.admin.zmeng.mapper.ZmUserMapper;
import com.zm.admin.zmeng.service.ZmDictInfoService;
import com.zm.admin.zmeng.service.ZmDictService;
import com.zm.admin.zmeng.service.ZmUserService;
import com.zm.admin.zmeng.service.impl.ZmUserServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/***
 *
 * @Auther: MuYun
 * @Date: 2022/12/28 20:59
 * @Description： 字典相关的后台接口
 *
 */
@RestController
@Slf4j
@RequestMapping("/dict")
public class DictController {

    @Resource
    private ZmDictMapper zmDictMapper;

    @Resource
    private ZmUserMapper zmUserMapper;

    @Resource
    private ZmDictInfoMapper zmDictInfoMapper;

    @Resource
    private ZmDictService zmDictService;

    @Resource
    private ZmDictInfoService zmDictInfoService;

    /**
     * 获取字典列表
     * @param dictDto
     * @return
     */
    @RequestMapping("/list")
    public ResultBean list(DictDto dictDto){
        ResultBean resultBean=new ResultBean();
        Integer pageNo=1;
        Integer pageSize=10;
        try{
            QueryWrapper<ZmDict> wrapper = designQueryMapper(dictDto);
            if(ObjectUtil.isNotEmpty(dictDto.getPageNo())){
                pageNo=dictDto.getPageNo();
            }
            if(ObjectUtil.isNotEmpty(dictDto.getPageSize())){
                pageSize= dictDto.getPageSize();
            }
            Page<ZmDict> page = zmDictService.page(new Page<>(pageNo, pageSize), wrapper);
            resultBean.setCode(ResultBean.CODE_SUCCESS).setData(page);
        }catch (Exception e){
            log.error("获取字典列表接口报错",e);
            resultBean.setCode(ResultBean.CODE_ERROR);
        }
        return resultBean;
    }

    /**
     * 字典新增
     * @param dict
     * @return
     */
    @RequestMapping("/add")
    @SysLogTag(desc = "字典新增")
    public ResultBean add(ZmDict dict){
        ResultBean resultBean=new ResultBean();
        try{
            dict.setCreateTime(DateUtil.date());
            dict.setCreateBy(getLoginUser());
            zmDictMapper.insert(dict);
            resultBean.setCode(ResultBean.CODE_SUCCESS).setMsg("新增字典成功");
        }catch (Exception e){
            log.error("新增字典接口报错",e);
            resultBean.setCode(ResultBean.CODE_ERROR).setMsg("新增字典接口报错");
        }
        return resultBean;
    }

    @RequestMapping("/update")
    @SysLogTag(desc = "字典修改")
    public ResultBean update(ZmDict dict){
        ResultBean resultBean=new ResultBean();
        try{
            ZmDict zmDict = zmDictMapper.selectById(dict.getId());
            dict.setUpdateTime(DateUtil.date());
            dict.setUpdateBy(getLoginUser());
            zmDictMapper.updateById(dict);
            //字典状态被修改后，该字典的详情记录状态也会被修改
            if(!zmDict.getStatus().equals(dict.getStatus())){
                List<String> list=new ArrayList<>();
                list.add(dict.getId());
                zmDictInfoMapper.updateDictInfoStatus(list, dict.getStatus());
            }
            resultBean.setCode(ResultBean.CODE_SUCCESS).setMsg("修改字典成功");
        }catch (Exception e){
            log.error("修改字典接口报错",e);
            resultBean.setCode(ResultBean.CODE_ERROR).setMsg("修改字典接口报错");
        }
        return resultBean;
    }

    /**
     * 字典删除
     * @param list
     * @return
     */
    @RequestMapping("/del")
    @SysLogTag(desc = "字典删除")
    public ResultBean del(@RequestBody List<ZmDict> list){
        ResultBean resultBean=new ResultBean();
        try{
            for(ZmDict dict:list){
                dict.setStatus("-1");
                dict.setUpdateTime(DateUtil.date());
                dict.setUpdateBy(getLoginUser());
            }
            zmDictService.updateBatchById(list);
            //再将字典内包含的详情记录假删除
            zmDictInfoMapper.updateDictInfoStatus(list.stream().map(ZmDict::getId).collect(Collectors.toList()),"-1");
            resultBean.setCode(ResultBean.CODE_SUCCESS).setMsg("删除字典记录成功");
        }catch (Exception e){
            log.error("删除字典记录接口报错",e);
            resultBean.setCode(ResultBean.CODE_ERROR).setMsg("删除字典记录接口报错");
        }
        return resultBean;
    }

    /**
     * 获取字典详情列表
     * @param dictInfoDto
     * @return
     */
    @RequestMapping("/infoList")
    public ResultBean infoList(DictInfoDto dictInfoDto){
        ResultBean resultBean=new ResultBean();
        Integer pageNo=1;
        Integer pageSize=10;
        if(StrUtil.isEmpty(dictInfoDto.getDictId())){
            return resultBean.setCode(ResultBean.CODE_ERROR).setMsg("未获取到字典编码！");
        }
        try{
            QueryWrapper<ZmDictInfo> wrapper = designInfoQueryMapper(dictInfoDto);
            if(ObjectUtil.isNotEmpty(dictInfoDto.getPageNo())){
                pageNo=dictInfoDto.getPageNo();
            }
            if(ObjectUtil.isNotEmpty(dictInfoDto.getPageSize())){
                pageSize=dictInfoDto.getPageSize();
            }
            Page<ZmDictInfo> page = zmDictInfoService.page(new Page<>(pageNo, pageSize), wrapper);
            resultBean.setCode(ResultBean.CODE_SUCCESS).setData(page);
        }catch (Exception e){
            log.error("获取字典详情列表接口报错",e);
            resultBean.setCode(ResultBean.CODE_ERROR);
        }
        return resultBean;
    }

    /**
     * 获取字典详情列表
     * @return
     */
    @RequestMapping("/infoListByDict")
    public ResultBean infoListByDict(){
        ResultBean resultBean=new ResultBean();
        try {
            List<DictInfoDto> dictInfoDtos = zmDictInfoMapper.selectAllInfoByDictId();
            resultBean.setCode(ResultBean.CODE_SUCCESS).setData(dictInfoDtos);
        }catch (Exception e){
            log.error("获取字典详情列表接口报错",e);
            resultBean.setCode(ResultBean.CODE_ERROR);
        }
        return resultBean;
    }

    /**
     * 字典详情新增
     * @param dictInfo
     * @return
     */
    @SysLogTag(desc = " 字典详情新增")
    @RequestMapping("infoAdd")
    public ResultBean infoAdd(ZmDictInfo dictInfo){
        ResultBean resultBean=new ResultBean();
        try{
            dictInfo.setCreateTime(DateUtil.date());
            dictInfo.setCreateBy(getLoginUser());
            zmDictInfoMapper.insert(dictInfo);
            resultBean.setCode(ResultBean.CODE_SUCCESS).setMsg("新增字典详情成功");
        }catch (Exception e){
            log.error("新增字典详情记录接口报错",e);
            resultBean.setCode(ResultBean.CODE_ERROR).setMsg("新增字典详情错误");
        }
        return resultBean;
    }


    /**
     * 字典详情修改
     * @param dictInfo
     * @return
     */
    @SysLogTag(desc = " 字典详情修改")
    @RequestMapping("infoUpdate")
    public ResultBean infoUpdate(ZmDictInfo dictInfo){
        ResultBean resultBean=new ResultBean();
        try{
            dictInfo.setUpdateTime(DateUtil.date());
            dictInfo.setUpdateBy(getLoginUser());
            zmDictInfoMapper.updateById(dictInfo);
            resultBean.setCode(ResultBean.CODE_SUCCESS).setMsg("修改字典详情成功。");
        }catch (Exception e){
            log.error("修改字典详情记录接口报错",e);
            resultBean.setCode(ResultBean.CODE_ERROR).setMsg("修改字典详情失败。");
        }
        return resultBean;
    }

    /**
     * 字典详情删除
     * @param list
     * @return
     */
    @SysLogTag(desc = " 字典详情删除")
    @RequestMapping("/infoDel")
    public ResultBean infoDel(@RequestBody List<ZmDictInfo> list){
        ResultBean resultBean=new ResultBean();
        try{
            for(ZmDictInfo dictInfo:list){
                dictInfo.setStatus("-1");
                dictInfo.setUpdateTime(DateUtil.date());
                dictInfo.setUpdateBy(getLoginUser());
            }
            zmDictInfoService.updateBatchById(list);
            resultBean.setCode(ResultBean.CODE_SUCCESS).setMsg("删除字典详情记录成功");
        }catch (Exception e){
            log.error("删除字典详情记录接口报错",e);
            resultBean.setCode(ResultBean.CODE_ERROR);
        }
        return resultBean;
    }

    /**
     * 获取当前登陆用户
     * @return
     */
    public String getLoginUser(){
        String username="未检测到用户捏";
        if(StpUtil.isLogin()){
            String id = StpUtil.getLoginId().toString();
            username= zmUserMapper.selectById(id).getUsername();
        }
        return username;
    }

    private static QueryWrapper<ZmDict> designQueryMapper(DictDto dictDto){
        QueryWrapper<ZmDict> wrapper=new QueryWrapper<>();
        if(StrUtil.isNotEmpty(dictDto.getDictName())){
            wrapper.lambda().like(ZmDict::getDictName,dictDto.getDictName());
        }
        if(StrUtil.isNotEmpty(dictDto.getCode())){
            wrapper.lambda().like(ZmDict::getCode,dictDto.getCode());
        }
        if(StrUtil.isNotEmpty(dictDto.getStatus())){
            wrapper.lambda().eq(ZmDict::getStatus,dictDto.getStatus());
        }
        if(StrUtil.isNotEmpty(dictDto.getEndTime())){
            wrapper.lambda().le(ZmDict::getCreateTime,dictDto.getEndTime());
        }
        if(StrUtil.isNotEmpty(dictDto.getStartTime())){
            wrapper.lambda().ge(ZmDict::getCreateTime,dictDto.getStartTime());
        }
        wrapper.lambda().ne(ZmDict::getStatus,"-1");
        return wrapper;
    }

    private static QueryWrapper<ZmDictInfo> designInfoQueryMapper(DictInfoDto dictInfoDto){
        QueryWrapper<ZmDictInfo> wrapper=new QueryWrapper<>();
        wrapper.lambda().eq(ZmDictInfo::getDictId,dictInfoDto.getDictId());
        if(StrUtil.isNotEmpty(dictInfoDto.getDictLabel())){
            wrapper.lambda().like(ZmDictInfo::getDictLabel,dictInfoDto.getDictLabel());
        }
        if(StrUtil.isNotEmpty(dictInfoDto.getStatus())){
            wrapper.lambda().eq(ZmDictInfo::getStatus,dictInfoDto.getStatus());
        }
        wrapper.lambda().ne(ZmDictInfo::getStatus,"-1");
        return wrapper;
    }
}
